package com.wl156.activities;

import java.io.IOException;

import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.xmlpull.v1.XmlPullParserException;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.wl156.MyApp;
import com.wl156.lite.R;
import com.wl156.model.Certificate;
import com.wl156.model.WebServiceClient;

public class UserActive extends Activity implements OnClickListener {

	private EditText mUserId;
	private EditText mRegisterCode;
	private Button mConfirm;
	private Button mCancel;

	private WebServiceClient mWebServiceClient;
	private Certificate mCertificate;

	String username;
	String password;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.act_user_active);

		mWebServiceClient = new WebServiceClient(this);
		mCertificate = ((MyApp) getApplication()).getCertificateFromXml();

		username = getIntent().getStringExtra("username");
		password = getIntent().getStringExtra("password");

		mUserId = (EditText) findViewById(R.id.userid);
		mRegisterCode = (EditText) findViewById(R.id.register_code);
		mConfirm = (Button) findViewById(R.id.confirm);
		mConfirm.setOnClickListener(this);
		mCancel = (Button) findViewById(R.id.cancel);
		mCancel.setOnClickListener(this);

		mUserId.setText(username);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.confirm:
			final String userid = mUserId.getText().toString();
			final String registerCode = mRegisterCode.getText().toString();
			new AsyncTask<Void, Void, Object>() {
				ProgressDialog mDialog;

				@Override
				protected void onPreExecute() {
					mDialog = ProgressDialog
							.show(UserActive.this, "", "激活中...");
				}

				@Override
				protected void onPostExecute(Object result) {
					if (result instanceof SoapPrimitive) {
						SoapPrimitive msg = (SoapPrimitive) result;
						Toast.makeText(UserActive.this, msg.toString(),
								Toast.LENGTH_LONG).show();
					} else if (result instanceof SoapObject) {
						Toast.makeText(UserActive.this, "激活成功，请使用该帐号登录",
								Toast.LENGTH_LONG).show();
						finish();
					} else {
						Toast.makeText(UserActive.this, "网络异常，请稍候再试",
								Toast.LENGTH_LONG).show();
					}

					mDialog.dismiss();
				};

				@Override
				protected Object doInBackground(Void... params) {
					try {
						return mWebServiceClient
								.sysActive(userid, registerCode);
					} catch (IOException e) {
						return e;
					} catch (XmlPullParserException e) {
						return e;
					}
				}
			}.execute();
			break;
		case R.id.cancel:
			finish();
			break;
		}
	}
}
